<template>
	<view class="index-box" :style="{ '--color': vuex_config.themeColor1 }" v-if="dataForm.pk_id ? true : false">
		<sww-swipe :list="swipeList" indicatorDots autoplay @onPlayVideo="onPlayVideo"></sww-swipe>
		<view class="content-box">
			<!--  限时抢购计时器-->
			<view class="flash-times flex-tb" v-if="dataForm.mode == 2 && prodState.type !== 3">
				<view class="ft_icon iconfont iconfont-e656"></view>
				<text class="">限时抢购</text>
				<view class="ml-auto">{{ prodState.msg }}</view>
				<template v-if="prodState.times ? true : false">
					<view>：{{ timeObj.day }}天</view>
					<view class="ft-time">{{ timeObj.hours }}</view>
					<view class="ft-time">{{ timeObj.minute }}</view>
					<view class="ft-time">{{ timeObj.second }}</view>
				</template>
			</view>
			<!--      基本信息-->
			<view class="prod_box">
				<view class="prod-title u-font-30 fw-bold">{{ dataForm.name }}</view>
				<view class="prod-price u-flex u-border-bottom">
					<!--    价格区间-->
					<block v-if="dataForm.minPrice?true:false">
						<text class="u-font-24 sww-tp">￥</text>
						<view style="display: inline;" class="u-font-36 fw-bold sww-tp">{{ $price(dataForm.minPrice) }} - {{ $price(dataForm.maxPrice) }}</view>
					</block>
					<!--    价格区间 end-->
					<block v-else>
						<text class="u-font-24 sww-tp">￥</text>
						<text class="u-font-36 fw-bold sww-tp">
							{{ $price(dataForm.amount) }}
							<text class="c-99 u-font-20 ml-20">起</text>
						</text>
						<!--    市场价-->
						<text class="u-font-24 u-m-l-10 c-99 td-lt"
							v-if="dataForm.market_price && dataForm.market_price > 0">￥{{ $price(dataForm.market_price) }}</text>
					</block>

					<view class="sww-rebate-wrap prod-rebate" v-if="dataForm.integral == 1"><text
							class="sww-rebate">购买得积分</text></view>
					<!-- 分销商返佣 -->
					<view class="sww-rebate-wrap prod-rebate" v-if="vuex_user.type == 2 && $rebate(dataForm.rebate) && vuex_user.commission > 0">
						<text class="sww-rebate">分享赚 {{ $rebateNum(dataForm.rebate, vuex_user.commission) }}</text>
					</view>
					<text class="u-font-24 c-99 ml-auto" v-if="vuex_config.sales_volume == 1 && dataForm.order_num > 0">
						<text class="u-m-r-5">已售</text>
						<text>{{ $price(dataForm.order_num) }}</text>
					</text>
				</view>
				<u-cell-item :arrow="false" hover-class="none" title="景点说明">
					<view class="">{{dataForm.title}}</view>
				</u-cell-item>
				<u-cell-item :arrow="false" hover-class="none" title="景区地址">
					<view class="">{{dataForm.address}}</view>
				</u-cell-item>
				<u-cell-item title="选择规格" @click="showSpec('buy')" hover-class="none"></u-cell-item>
				<u-cell-item title="用户评价" :border-bottom="false" hover-class="none"
					@click="$linkTo(`/package/product/comment/index?prodId=${dataForm.pk_id}&id=2`)"></u-cell-item>
			</view>

			<!--      产品详情-->

			<block v-if="dataForm.details">
				<view class="prod_box u-m-t-10">
					<u-cell-item :arrow="false">
						<view class="fw-bold" slot="title" hover-class="none">商品详情</view>
					</u-cell-item>
					<u-parse :html="dataForm.details"></u-parse>
				</view>
			</block>



			<!--      价格说明-->
			<block v-if="dataForm.others">
				<view class="prod_box u-m-t-10">
					<u-cell-item :arrow="false">
						<view class="fw-bold" slot="title" hover-class="none">价格说明</view>
					</u-cell-item>
					<u-parse :html="dataForm.others"></u-parse>
				</view>
			</block>
			<!--      预定须知-->



		</view>
		<!--  底部  -->
		<sww-goods-action>
			<button class="goods-action-icon u-reset-button" @click="$linkTo('index')">
				<view class="">
					<u-icon name="e736" size="36" color="#666666" custom-prefix="iconfont"></u-icon>
				</view>
				<view class="bb-text">首页</view>
			</button>
			<button class="goods-action-icon u-reset-button" @click="collectChange">
				<block v-if="isFavorite">
					<view class="sww-tc-c">
						<u-icon name="e732" size="36" custom-prefix="iconfont"></u-icon>
					</view>
				</block>
				<block v-else>
					<view class="">
						<u-icon name="e733" size="36" color="#666666" custom-prefix="iconfont"></u-icon>
					</view>
				</block>
				<view class="bb-text">收藏</view>
			</button>
			<view class="goods-action-btn-wrap">
				<view class="goods-action-btn" @click="showSpec('buy')">立即购买</view>
			</view>
		</sww-goods-action>

		<sww-login></sww-login>
		<sww-sidebar :scroll-top="scrollTop" :prod-info="{ ...dataForm, prodType: 2 }" share :contact="vuex_config.has_contact"></sww-sidebar>
	</view>
</template>
<script>
	import {
		uniModal,
		uniNavigate,
		uniToast
	} from '../../../../utils/uniPromise';
	import {
		getProdStatus
	} from '../../../../module/product/prodMet';
	import {
		mapState
	} from 'vuex';
	import {
		pageShare
	} from '../../../../mixins/pageShare';
	import {
		timeMiXin
	} from '../../../../mixins/timemixin';
	import {
		sideBarMixin
	} from '../../../../components/sww-sidebar';
	import {
		formatDate,
		countTime
	} from '@/utils/moment/index.js';
	export default {
		mixins: [pageShare, sideBarMixin, timeMiXin],
		data() {
			return {
				timeObj: {}, // 倒计时时间对象
				time: null, // 倒计时计算器
				swipeList: [], //轮播
				prodState: {
					type: 0, // 0未开始，1进行中，2已结束
					times: 0 // 初始化查询是，距离下个状态的时间戳差值
				}, //产品状态
				dataForm: {}, //产品详情
				shareParams: {},
				specVisible: false, //规格弹框
				specParams: {
					buyType: '',
					prodId: '', //产品ID
					stockId: '', //产品规格ID
					cartId: '', //购物车ID
					num: 0 //产品规格购买数量
				},
				dataObj: {},
				commentList: null,
				browTime: 0
			};
		},
		computed: {
			...mapState(['vuex_business']),
			getLogistic() {
				// 获取运费情况
				if (this.dataForm.express_num && this.dataForm.express_num > 1) {
					return this.dataForm.express_num + '件起免运费';
				} else {
					return this.dataForm.express_price > 0 ? this.dataForm.express_price : '免运费';
				}
			},
			isFavorite() {
				return this.dataForm.is_favourite == 1;
			}
		},
		onLoad(options) {
			if (options.id) {
				this.initPage(options.id);
				this.getBrowTime();
				return
			}

			//  #ifdef MP-ALIPAY	
			let vuex_router_query = this.vuex_router_query
			// 支付宝通过二维码扫码进来的话在onLoad获取不到参数的，只能在全局 app.js onLaunch获取
			if (vuex_router_query.baidu == 1) {
				this.initPage(vuex_router_query.id);
				this.getBrowTime();
				return
			}
			// #endif


			this.$linkTo('index');

		},
		onShareAppMessage: function() {
			return this.getShareAppMessage();
		},
		onShareTimeline: function() {
			return this.getShareTimeline();
		},
		onUnload() {
			if (this.time) {
				clearTimeout(this.time);
			}
			if (this.browTime && this.$isLogin()) {
				this.addBrow(this.dataForm.pk_id);
			}
		},
		methods: {
			// 视频播放
			onPlayVideo(url) {
				this.$to(`/package/video/video-play/index?url=${url}`);
			},
			// 记录开始浏览时间
			getBrowTime() {
				this.browTime = new Date().getTime();
			},
			// 新增浏览记录
			addBrow(prodId) {
				let date = new Date();
				let duration = parseInt((date.getTime() - this.browTime) / 1000);
				date = formatDate(date, 'YYYY-MM-DD HH:mm:ss');
				this.$resPost('AddUsersBrowse', {
					type: 1,
					product_id: prodId,
					date_time: date,
					duration: duration
				}).catch(() => {});
			},
			// 检测登录
			checkLogin() {
				return this.$login('initPage', this.dataForm.pk_id);
			},
			// 初始化页面数据
			initPage(id) {
				this.$loading();
				this.$resPost('GetTicketProDetailed', {
						pk_id: id
					})
					.then(({
						data
					}) => {
						if (!data.pk_id || data.is_online != 1) {
							return Promise.reject();
						}
						let swipeList = [];
						if (data.video) {
							swipeList.push({
								video: data.video
							});
						}
						if (data.img) {
							data.img.split(',').forEach(item => {
								swipeList.push({
									img: item
								});
							});
						}
						this.swipeList = [].concat(swipeList);
						data.product_stock = data.product_stock || [];
						if (data.product_stock && data.product_stock.length > 1) {
							// 多规格处理：获取最小价格和最大价格
							let minPrice = data.product_stock[0].amount;
							let maxPrice = data.product_stock[0].amount;
							data.product_stock.forEach(item => {
								if (item.amount < minPrice) {
									minPrice = item.amount;
								} else if (item.amount > maxPrice) {
									maxPrice = item.amount;
								}
							});
							if (minPrice == maxPrice) {
								minPrice = '';
								maxPrice = '';
							}
							data.minPrice = minPrice;
							data.maxPrice = maxPrice;
						}
						if (data.mode == 2) {
							// 秒杀抢购商品：根据产品有效时间获取产品状态：获取状态和距离下个状态的时间
							this.setSeckill(data);
						}
						this.dataForm = {
							...data
						};
						this.customShareParams(); // 设置当前产品页的分享参数
						this.$hide();
					})
					.catch(() => {
						this.$hide();
						uniModal({
							title: '商品已下架',
							showCancel: false,
							confirmText: '我知道了'
						}).then(() => {
							this.uniBack();
						});
					});
				// if (!this.commentList) {
				// 	this.$resPost('GetCommentList', { pk_id: id, type: 5, page: 1, page_size: 1 })
				// 		.then(({ data }) => {
				// 			this.commentList = data;
				// 		})
				// 		.catch(() => {});
				// }
			},
			// 判断秒杀状态
			setSeckill(data) {
				// 秒杀抢购商品：根据产品有效时间获取产品状态：获取状态和距离下个状态的时间
				let start_date = data.start_date;
				let end_date = data.end_date;
				let saleArr = (data.sale_time || '').split(',');
				let sale_startArr = (saleArr[0] || '').split(':');
				let sale_endArr = (saleArr[1] || '').split(':');
				if (data.sale_time) {
					let current = new Date();
					let sale_start = current.setHours(sale_startArr[0], sale_startArr[1], 0);
					let sale_end = current.setHours(sale_endArr[0], sale_endArr[1], 0);
					if (sale_start > start_date) {
						start_date = sale_start;
					}
					if (sale_end < end_date) {
						end_date = sale_end;
					}
				}
				let prodState = getProdStatus(start_date, end_date, false);

				if (prodState.type == 2 && data.sale_time) {
					let tomDate = new Date();
					tomDate.setDate(tomDate.getDate() + 1);
					let tomorrow_start = tomDate.setHours(sale_startArr[0], sale_startArr[1], 0);
					let tomorrow_end = tomDate.setHours(sale_endArr[0], sale_endArr[1], 0);
					if (data.end_date < tomorrow_end) {
						/*这个有没有不大重要，严谨而已*/
						tomorrow_end = data.end_date;
					}
					if (tomorrow_start < data.end_date) {
						// 明天还可以抢购
						prodState = getProdStatus(tomorrow_start, tomorrow_end, false);
					}
				}
				if (prodState.type != 2) {
					// 抢购商品，且未结束开启倒计时
					this.getCountTime(prodState.times);
				}
				this.prodState = {
					...prodState
				};
			},
			// 定时器循环倒计时
			getCountTime(nextTime) {
				if (nextTime >= 0) {
					this.timeObj = countTime(nextTime);
					this.time = setTimeout(() => {
						this.getCountTime(this.timeObj.nextTime);
					}, 1000);
				} else {
					this.initPage(this.dataForm.pk_id);
				}
			},
			// 设置当前产品页的分享参数
			customShareParams() {
				if (!this.shareParams.title) {
					let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
					let curRoute = routes[routes.length - 1].route; //获取当前页面路由
					let curParam = routes[routes.length - 1].options; //获取路由参数
					let obj = this.swipeList.find(item => {
						return item.img;
					});
					this.shareParams = {
						title: this.dataForm.name,
						path: curRoute,
						query: curParam,
						imgUrl: obj && obj.img ? obj.img : ''
					};
					this.onShareByH5();
				}
			},
			//收藏切换
			collectChange() {
				this.$u.debounce(
					() => {
						this.checkLogin().then(() => {
							let apiName = this.isFavorite ? 'DeleteUsersFavourite' : 'AddUsersFavourite';
							this.$loading();
							this.$resPost(apiName, {
									type: 1,
									product_id: this.dataForm.pk_id
								})
								.then(() => {
									this.$toast(this.isFavorite ? '已取消收藏' : '收藏成功');
									this.dataForm.is_favourite = this.isFavorite ? '2' : '1';
									this.$hide();
								})
								.catch(() => {
									this.$hide();
								});
						});
					},
					500,
					true
				);
			},
			// 跳转购物车
			linkToCart() {
				this.checkLogin().then(() => {
					this.$linkTo('/package/user/cart/index', 'redirect');
				});
			},
			// 打开规格弹框
			showSpec(type) {
				this.$u.debounce(
					() => {
						this.checkLogin().then(() => {
							this.specParams.buyType = type;
							let params = {
								travel_status: '1',
								...this.dataForm
							}
							this.dataObj = params //用于页面栈传值
							if (this.dataForm.mode == 2) {
								// 抢购:立即购买
								if (this.prodState.type == 2) {
									this.$toast({
										title: '活动已结束'
									});
								} else if (this.prodState.type == 0) {
									this.$toast({
										title: '活动还未开始'
									});
								} else {

									// #ifdef   MP-ALIPAY || MP-BAIDU	|| MP-TOUTIAO	 
									this.$to(
										`/package/product/ticket/date/index`
									)
									// #endif

									// #ifndef MP-ALIPAY || MP-BAIDU || MP-TOUTIAO	 
									uniNavigate('/package/product/ticket/date/index').then(res => {
										res.eventChannel.emit('acceptParams', params);
									});
									// #endif 


								}
							} else {
								// 立即购买 判断是否在销售时间段内
								this.checktime()
									.then(res => {

										// #ifdef   MP-ALIPAY || MP-BAIDU	|| MP-TOUTIAO	 
										this.$to(
											`/package/product/ticket/date/index`
										)
										// #endif


										// #ifndef MP-ALIPAY || MP-BAIDU || MP-TOUTIAO	 	
										uniNavigate('/package/product/ticket/date/index').then(res => {
											res.eventChannel.emit('acceptParams', params);
										});
										// #endif 

									})
									.catch(res => {
										uniToast(res);
									});
							}
						});
					},
					300,
					true
				);
			},
		}
	};
</script>
<style>
	page {
		background-color: #f5f5f5;
	}
</style>
<style lang="scss" scoped>
	@import 'package/product/common/prodDetail';

	.ml-20 {
		margin-left: 10rpx;
	}


	.u-reset-button {
		border: 0;
	}
</style>
